<!DOCTYPE html>




<html class="theme-next mist" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="python,Django," />








  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon-16x16-next.png?v=5.1.2" />






<meta name="description" content="小程序基础全局入口 —— app.js全局配置 —— app.json全局样式 —— app.wxss 全局配置（页面导航）pages 列表配置页面 window 属性配置导航条背景/文字/等颜色 tabbar 配置12345678910111213141516 &amp;quot;tabBar&amp;quot;: &amp;#123;  &amp;quot;list&amp;quot;: [    &amp;#123;      &amp;quot">
<meta name="keywords" content="python,Django">
<meta property="og:type" content="article">
<meta property="og:title" content="python-Django框架-微信小助手实践">
<meta property="og:url" content="http://xchcloud.cn/python-Django框架-微信小助手实践/index.html">
<meta property="og:site_name" content="超哥记录日记">
<meta property="og:description" content="小程序基础全局入口 —— app.js全局配置 —— app.json全局样式 —— app.wxss 全局配置（页面导航）pages 列表配置页面 window 属性配置导航条背景/文字/等颜色 tabbar 配置12345678910111213141516 &amp;quot;tabBar&amp;quot;: &amp;#123;  &amp;quot;list&amp;quot;: [    &amp;#123;      &amp;quot">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/%E9%A1%B5%E9%9D%A2%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F.png">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/%E9%A1%B5%E9%9D%A2%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F2.png">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/%E4%BA%8B%E4%BB%B6%E7%BB%91%E5%AE%9A.png">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E6%A1%86%E6%9E%B6.png">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/Http%E8%AF%B7%E6%B1%82.png">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/%E4%B8%8A%E4%BC%A0%E6%96%87%E4%BB%B6.png">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E4%B8%AD%E7%9A%84%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86.jpg">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7openid.png">
<meta property="og:image" content="http://tuchuang.xchcloud.cn/ORM%20%E6%A8%A1%E5%9E%8B.jpg">
<meta property="og:updated_time" content="2019-03-31T12:40:04.895Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python-Django框架-微信小助手实践">
<meta name="twitter:description" content="小程序基础全局入口 —— app.js全局配置 —— app.json全局样式 —— app.wxss 全局配置（页面导航）pages 列表配置页面 window 属性配置导航条背景/文字/等颜色 tabbar 配置12345678910111213141516 &amp;quot;tabBar&amp;quot;: &amp;#123;  &amp;quot;list&amp;quot;: [    &amp;#123;      &amp;quot">
<meta name="twitter:image" content="http://tuchuang.xchcloud.cn/%E9%A1%B5%E9%9D%A2%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xchcloud.cn/python-Django框架-微信小助手实践/"/>





  <title>python-Django框架-微信小助手实践 | 超哥记录日记</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8d23512908ca3b4b175b2620a75740f";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">超哥记录日记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">生命有息、学无止境、折腾不止</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xchcloud.cn/python-Django框架-微信小助手实践/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="John Doe">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://tuchuang-xchcloud-1253428588.cos.ap-chengdu.myqcloud.com/blog/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="超哥记录日记">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">python-Django框架-微信小助手实践</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-31T16:23:33+08:00">
                2019-03-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index">
                    <span itemprop="name">python</span>
                  </a>
                </span>

                
                
              
            </span>
          

 


          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o">访问数</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>°C
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计</span>
                
                <span title="字数统计">
                  3,982
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长</span>
                
                <span title="阅读时长">
                  17
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="小程序基础"><a href="#小程序基础" class="headerlink" title="小程序基础"></a>小程序基础</h2><p>全局入口 —— app.js<br>全局配置 —— app.json<br>全局样式 —— app.wxss</p>
<h3 id="全局配置（页面导航）"><a href="#全局配置（页面导航）" class="headerlink" title="全局配置（页面导航）"></a>全局配置（页面导航）</h3><h4 id="pages-列表配置"><a href="#pages-列表配置" class="headerlink" title="pages 列表配置"></a>pages 列表配置</h4><p>页面</p>
<h4 id="window-属性配置"><a href="#window-属性配置" class="headerlink" title="window 属性配置"></a>window 属性配置</h4><p>导航条背景/文字/等颜色</p>
<h4 id="tabbar-配置"><a href="#tabbar-配置" class="headerlink" title="tabbar 配置"></a>tabbar 配置</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"> &quot;tabBar&quot;: &#123;</span><br><span class="line">  &quot;list&quot;: [</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;pagePath&quot;: &quot;pages/index/index&quot;,</span><br><span class="line">      &quot;text&quot;: &quot;首页&quot;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;pagePath&quot;: &quot;pages/logs/logs&quot;,</span><br><span class="line">      &quot;text&quot;: &quot;日志&quot;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      &quot;pagePath&quot;: &quot;pages/demogrid/demogrid&quot;,</span><br><span class="line">      &quot;text&quot;: &quot;九宫格&quot;</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="小程序的页面设置"><a href="#小程序的页面设置" class="headerlink" title="小程序的页面设置"></a>小程序的页面设置</h3><p>json</p>
<h4 id="开启下拉刷新"><a href="#开启下拉刷新" class="headerlink" title="开启下拉刷新"></a>开启下拉刷新</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  &quot;enablePullDownRefresh&quot;: true</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="小程序的注册逻辑层"><a href="#小程序的注册逻辑层" class="headerlink" title="小程序的注册逻辑层"></a>小程序的注册逻辑层</h3><p>app.js</p>
<h4 id="小程序的注册逻辑"><a href="#小程序的注册逻辑" class="headerlink" title="小程序的注册逻辑"></a>小程序的注册逻辑</h4><p>App函数<br>注册全局唯一的小程序<br>只能调用一次<br>接收一个对象作为函数参数</p>
<h4 id="页面注册逻辑"><a href="#页面注册逻辑" class="headerlink" title="页面注册逻辑"></a>页面注册逻辑</h4><p>Page函数<br>注册一个页面<br>接受一个对象作为函数参数</p>
<h5 id="页面数据"><a href="#页面数据" class="headerlink" title="页面数据"></a>页面数据</h5><p>data属性</p>
<p>使用全局数据<br>获取全局唯一的 App 实例<br>通过唯一实例获取全局数据</p>
<h5 id="页面生命周期"><a href="#页面生命周期" class="headerlink" title="页面生命周期"></a>页面生命周期</h5><p><img src="http://tuchuang.xchcloud.cn/%E9%A1%B5%E9%9D%A2%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F.png" alt="页面生命周期"></p>
<p><img src="http://tuchuang.xchcloud.cn/%E9%A1%B5%E9%9D%A2%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F2.png" alt="页面生命周期"></p>
<h3 id="小程序的视图层"><a href="#小程序的视图层" class="headerlink" title="小程序的视图层"></a>小程序的视图层</h3><h4 id="数据绑定"><a href="#数据绑定" class="headerlink" title="数据绑定"></a>数据绑定</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">语法 &#123;&#123;&#125;&#125;</span><br><span class="line">  &lt;view&gt;&#123;&#123; message &#125;&#125;&lt;/view&gt;</span><br><span class="line">  message: &quot;Hello World, Hello Django&quot;,</span><br></pre></td></tr></table></figure>
<h4 id="列表渲染"><a href="#列表渲染" class="headerlink" title="列表渲染"></a>列表渲染</h4><p>语法：wx:for</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;view wx:for=&quot;&#123;&#123;array&#125;&#125;&quot;&gt;</span><br><span class="line">  No.&#123;&#123;index&#125;&#125; item, message: &#123;&#123;item.message&#125;&#125;</span><br><span class="line"> &lt;/view&gt;</span><br><span class="line">    array: [</span><br><span class="line">     &#123;</span><br><span class="line">       message: &quot;Hello World&quot;,</span><br><span class="line">     &#125;,</span><br><span class="line">     &#123;</span><br><span class="line">       message: &quot;Hello Django&quot;,</span><br><span class="line">     &#125;</span><br><span class="line">   ]</span><br></pre></td></tr></table></figure>
<h4 id="条件渲染"><a href="#条件渲染" class="headerlink" title="条件渲染"></a>条件渲染</h4><p>语法：wx:if wx:else wx:elif</p>
<h4 id="绑定事件"><a href="#绑定事件" class="headerlink" title="绑定事件"></a>绑定事件</h4><p><img src="http://tuchuang.xchcloud.cn/%E4%BA%8B%E4%BB%B6%E7%BB%91%E5%AE%9A.png" alt=""></p>
<p>绑定事件的写法以key、value的形式<br>key以bind或者catch开头，然后跟上事件的类型<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;view bindtap=&apos;tapName&apos;&gt;TapTap&lt;/view&gt;</span><br><span class="line"></span><br><span class="line">  tapName: function(event)&#123;</span><br><span class="line">  console.log(&apos; in tabName function&apos;)</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure></p>
<h4 id="小程序框架"><a href="#小程序框架" class="headerlink" title="小程序框架"></a>小程序框架</h4><p><img src="http://tuchuang.xchcloud.cn/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E6%A1%86%E6%9E%B6.png" alt=""></p>
<h3 id="小程序提供的能力和常用的API"><a href="#小程序提供的能力和常用的API" class="headerlink" title="小程序提供的能力和常用的API"></a>小程序提供的能力和常用的API</h3><h4 id="微信API"><a href="#微信API" class="headerlink" title="微信API"></a>微信API</h4><h5 id="网络请求"><a href="#网络请求" class="headerlink" title="网络请求"></a>网络请求</h5><h6 id="HTTP请求"><a href="#HTTP请求" class="headerlink" title="HTTP请求"></a>HTTP请求</h6><p><img src="http://tuchuang.xchcloud.cn/Http%E8%AF%B7%E6%B1%82.png" alt=""><br>Http请求异步特性：<br>不管是什么情况，先返回过程后返回结果。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&lt;button bindtap=&apos;testNetwork&apos;&gt;Test Network&lt;/button&gt;</span><br><span class="line">testNetwork: function(event)&#123;</span><br><span class="line">  var data = &apos;undefined&apos;</span><br><span class="line">  wx.request(&#123;</span><br><span class="line">    url: &apos;http://www.imooc.com&apos;,</span><br><span class="line">    method: &apos;GET&apos;,</span><br><span class="line">    header: &#123;&#125;,</span><br><span class="line">    success: function(res)&#123;</span><br><span class="line">      console.log(&apos;in success&apos;)</span><br><span class="line">      data = res.data</span><br><span class="line">    &#125;,</span><br><span class="line">    fail: function(res)&#123;</span><br><span class="line">      console.log(&apos;request failed.&apos;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">  console.log(&apos;data: &apos;, data)</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>
<h6 id="文件上传、下载"><a href="#文件上传、下载" class="headerlink" title="文件上传、下载"></a>文件上传、下载</h6><p><img src="http://tuchuang.xchcloud.cn/%E4%B8%8A%E4%BC%A0%E6%96%87%E4%BB%B6.png" alt=""></p>
<h6 id="Task（网络任务对象）"><a href="#Task（网络任务对象）" class="headerlink" title="*Task（网络任务对象）"></a>*Task（网络任务对象）</h6><p>中断任务<br>触发回调函数<br>关闭连接</p>
<h5 id="本地存储"><a href="#本地存储" class="headerlink" title="本地存储"></a>本地存储</h5><p>将数据存储在本地缓存中指定的key中，数据存储生命周期跟小程序本身一致。<br>◆wx.setStorage<br>◆wx.getStorage<br>◆wx.removeStorage<br>◆wx.clearStorage（前三个操作指定的缓存，最后一个删除所有缓存）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">  &lt;button bindtap=&apos;testStorage&apos;&gt;Test Storage&lt;/button&gt;</span><br><span class="line">testStorage: function()&#123;</span><br><span class="line">    wx.setStorage(&#123;</span><br><span class="line">      key: &apos;test&apos;,</span><br><span class="line">      data: &apos;data&apos;,</span><br><span class="line">    &#125;)</span><br><span class="line">    wx.getStorage(&#123;//异步</span><br><span class="line">      key: &apos;test&apos;,</span><br><span class="line">      success: function(res) &#123;</span><br><span class="line">        var data = res.data</span><br><span class="line">        console.log(&apos;data from storage 1: &apos;, data)</span><br><span class="line">      &#125;,</span><br><span class="line">    &#125;)</span><br><span class="line">    var data = wx.getStorageSync(&apos;test&apos;)//同步</span><br><span class="line"></span><br><span class="line">    console.log(&apos;data from storage 2: &apos;, data)</span><br><span class="line"></span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure>
<h4 id="文件系统"><a href="#文件系统" class="headerlink" title="文件系统"></a>文件系统</h4><h5 id="提供一个全局的问价管理系统，来实现对文件的增删改查"><a href="#提供一个全局的问价管理系统，来实现对文件的增删改查" class="headerlink" title="提供一个全局的问价管理系统，来实现对文件的增删改查"></a>提供一个全局的问价管理系统，来实现对文件的增删改查</h5><p>var fs=wx. getFileSystemManager()</p>
<p>◆fs.saveFile<br>◆fs.removeSavedFile<br>◆fs.writeFile<br>◆fs.appendFile<br>◆fs.readFile</p>
<h5 id="文件夹操作"><a href="#文件夹操作" class="headerlink" title="文件夹操作"></a>文件夹操作</h5><p>◆fs.mkdir<br>◆fs.rmdir<br>◆fs.isDirectory<br>◆fs.isFile</p>
<h4 id="开放能力"><a href="#开放能力" class="headerlink" title="开放能力"></a>开放能力</h4><p>◆用户数据<br>◆推送消息<br>◆运营数据</p>
<h5 id="用户数据"><a href="#用户数据" class="headerlink" title="用户数据"></a>用户数据</h5><p>◆头像、昵称等公开信息—wx.getUserlnfo）<br>◆openid等敏感数据</p>
<h5 id="基础组件"><a href="#基础组件" class="headerlink" title="基础组件"></a>基础组件</h5><p>开源</p>
<h2 id="Django视图层"><a href="#Django视图层" class="headerlink" title="Django视图层"></a>Django视图层</h2><p>Django Response对象<br>◆状态码——Response对象的status属性<br>◆应答内容——Response对象的content属性<br>◆延伸的Response子类——（JsonResponse、FileResponse）</p>
<h2 id="会话管理"><a href="#会话管理" class="headerlink" title="会话管理"></a>会话管理</h2><h3 id="有状态服务"><a href="#有状态服务" class="headerlink" title="有状态服务"></a>有状态服务</h3><h4 id="什么是状态"><a href="#什么是状态" class="headerlink" title="什么是状态"></a>什么是状态</h4><p>无状态服务:就是没有特殊状态的服务,各个请求对于服务器来说统一无差别处理,请求自身携带了所有服务端所需要的所有参数(服务端自身不存储跟请求相关的任何数据,不包括数据库存储信息)</p>
<p>有状态服务:与之相反,有状态服务在服务端保留之前请求的信息,用以处理当前请求,比如session等</p>
<p>小程序状态：小程序与后台通信需要通过微信后台来进行转发。</p>
<h2 id="小程序的状态管理"><a href="#小程序的状态管理" class="headerlink" title="小程序的状态管理"></a>小程序的状态管理</h2><p>在 utils 包中添加 Cookie.js 工具包，然后在里面有三个函数，取出、存储、取出。</p>
<p>const key = ‘cookie’</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">function getSessionIDFromResponse(res)&#123;</span><br><span class="line">  var cookie = res.header[&apos;Set-Cookie&apos;]</span><br><span class="line">  console.log(&apos;get cookie from response: &apos; + cookie)</span><br><span class="line">  return cookie</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function setCookieToStorage(cookie) &#123;</span><br><span class="line">  try&#123;</span><br><span class="line">    wx.setStorageSync(key, cookie)</span><br><span class="line">  &#125;catch(e)&#123;</span><br><span class="line">    console.log(e)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function getCookieFromStorage() &#123;</span><br><span class="line">  var value = wx.getStorageSync(key)</span><br><span class="line">  return value</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Django 的 Session 中间件</p>
<p>启用 Session 中间件：setting中的 MIDDLEWARE。</p>
<p>使用 Session 的方法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">def test_session(request):</span><br><span class="line">    request.session[&apos;message&apos;] = &apos;Test Django Session OK!&apos;</span><br><span class="line">    response = wrap_json_response(code=ReturnCode.SUCCESS)</span><br><span class="line">    return JsonResponse(data=response, safe=False)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def test_session2(request):</span><br><span class="line">    print(&apos;session content: &apos;, request.session.items())</span><br><span class="line">    response = wrap_json_response(code=ReturnCode.SUCCESS)</span><br><span class="line">    return JsonResponse(data=response, safe=False)</span><br></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">onReadCookies: function ()&#123;</span><br><span class="line">  wx.request(&#123;</span><br><span class="line">    url: app.globalData.serverUrl + app.globalData.apiVersion + &apos;/auth/test&apos;,</span><br><span class="line">    success: function(res)&#123;</span><br><span class="line">      var cookie = cookieUtil.getSessionIDFromResponse(res)</span><br><span class="line">      console.log(cookie)</span><br><span class="line">      cookieUtil.setCookieToStorage(cookie)</span><br><span class="line"></span><br><span class="line">      var newCookie = cookieUtil.getCookieFromStorage()</span><br><span class="line"></span><br><span class="line">      var header = &#123;&#125;</span><br><span class="line">      header.Cookie = newCookie</span><br><span class="line"></span><br><span class="line">      wx.request(&#123;</span><br><span class="line">        url: app.globalData.serverUrl + app.globalData.apiVersion + &apos;/auth/test2&apos;,</span><br><span class="line">        header: header,</span><br><span class="line">        success: function(res)&#123;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>
<p><img src="http://tuchuang.xchcloud.cn/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E4%B8%AD%E7%9A%84%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86.jpg" alt="小程序中的状态管理"></p>
<h3 id="小程序登录功能"><a href="#小程序登录功能" class="headerlink" title="小程序登录功能"></a>小程序登录功能</h3><p><img src="http://tuchuang.xchcloud.cn/%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7openid.png" alt=""></p>
<p><strong>使用哪种用户体系呢</strong></p>
<p>自建用户体系：<br>邮箱、电话等标记用户；填写、去重等复杂的交互逻辑。</p>
<p>沿用微信用户体系：<br>openid——微信用户的唯一识别标志。</p>
<p><strong>用户模型与用户视图：</strong><br>用户的唯一标识；<br>用户的基本信息。<br>获取用户的 OpenID</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class User(models.Model):</span><br><span class="line">    # openid</span><br><span class="line">    open_id = models.CharField(max_length=32, unique=True)</span><br><span class="line">    # 昵称</span><br><span class="line">    nickname = models.CharField(max_length=256)</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class UserView(View,CommonResponseMixin):</span><br><span class="line">    def get(self, request):</span><br><span class="line">        pass</span><br><span class="line">    def post(self, request):</span><br><span class="line">        pass</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># 路径：</span><br><span class="line">path(&apos;user&apos;, views.UserView.as_view())</span><br><span class="line"></span><br><span class="line"># 为什么是 as.view()</span><br></pre></td></tr></table></figure>
<h4 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h4><p>调用微信的 wx.login 获取临时的 code，不需要任何的参数，直接定义成功的回调函数，然后就是赋值，定义请求函数，包含请求链接、请求方式、请求内容，以及确定 GET POST 请求方式是否需要请求头，可以定义一个回调函数番薯输出登录成功。<br>定义cookies：获取、存储、获取</p>
<p><strong>问题：</strong><br>code 是啥？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">authorize: function () &#123;</span><br><span class="line">  wx.login(&#123;</span><br><span class="line">    success: function(res)&#123;</span><br><span class="line">      var code = res.code</span><br><span class="line">      var appId = app.globalData.appId</span><br><span class="line">      var nickname = app.globalData.userInfo.nickName</span><br><span class="line">      wx.request(&#123;</span><br><span class="line">        url: app.globalData.serverUrl + app.globalData.apiVersion + &apos;/auth/authorize&apos;,</span><br><span class="line">        method: &apos;POST&apos;,</span><br><span class="line">        data: &#123;                     //数据内容</span><br><span class="line">          code: code,</span><br><span class="line">          appId: appId,</span><br><span class="line">          nickname: nickname</span><br><span class="line">        &#125;,</span><br><span class="line">        header: &#123;                  //请求头</span><br><span class="line">          &apos;content-type&apos;: &apos;application/json&apos;</span><br><span class="line">        &#125;,</span><br><span class="line">        success: function(res)&#123;  //回调函数</span><br><span class="line">          wx.showToast(&#123;</span><br><span class="line">            title: &apos;授权成功&apos;</span><br><span class="line">          &#125;)</span><br><span class="line">          var cookie = cookieUtil.getSessionIDFromResponse(res)</span><br><span class="line">          cookieUtil.setCookieToStorage(cookie)</span><br><span class="line">          console.log(cookie)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>
<p><strong>出现的错误：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">ModuleNotFoundError: No module named &apos;Crypto&apos;</span><br><span class="line">解决方法：</span><br><span class="line"></span><br><span class="line">pip install pycryptodome</span><br><span class="line">当然有可能会出现这种情况：看到报错后是这么安装的：pip install crypto</span><br><span class="line"></span><br><span class="line">但是运行还是报错：ModuleNotFoundError: No module named &apos;Crypto&apos;；</span><br><span class="line">此时需要去环境中将安装的包crypto的名字改成Crypto,首字母大写；</span><br><span class="line">然后再次运行，出现这个错误：ModuleNotFoundError: No module named &apos;Crypto.Cipher&apos;</span><br><span class="line">此时进入到安装的文件夹下，发现没有此文件：</span><br><span class="line">需要卸载刚才安装的包：pip uninstall crypto</span><br><span class="line">然后重新安装：pip install pycryptodome，即可！</span><br><span class="line"></span><br><span class="line">&quot;errcode&quot;:40029：</span><br><span class="line">解决方法:</span><br><span class="line"></span><br><span class="line">微信开发者工具里开发项目需要填写appID，后台请求openid也需要appID，</span><br><span class="line">确认appID是否一致，确认appsecret是否一致，临时登录凭证code ，appID和appsecret必须相互对应。</span><br><span class="line"></span><br><span class="line">errcode&quot;:40125：</span><br><span class="line">解决方法：</span><br><span class="line"></span><br><span class="line">1.代码中设置的微信APPsecret和微信开放平台不一致，需要您自己对照微信开放平台和代码中的appsecret， 检查修正。 </span><br><span class="line">2.由于秘钥无效导致的，秘钥如果长时间不登录，会自动重置。</span><br></pre></td></tr></table></figure>
<h3 id="完善用户的个人信息"><a href="#完善用户的个人信息" class="headerlink" title="完善用户的个人信息"></a>完善用户的个人信息</h3><h4 id="用户模型的变更"><a href="#用户模型的变更" class="headerlink" title="用户模型的变更"></a>用户模型的变更</h4><h4 id="修改个人信息的功能开发"><a href="#修改个人信息的功能开发" class="headerlink" title="修改个人信息的功能开发"></a>修改个人信息的功能开发</h4><h3 id="复杂多变的用户状态管理"><a href="#复杂多变的用户状态管理" class="headerlink" title="复杂多变的用户状态管理"></a>复杂多变的用户状态管理</h3><h4 id="有状态的应用服务"><a href="#有状态的应用服务" class="headerlink" title="有状态的应用服务"></a>有状态的应用服务</h4><h4 id="Index-首页的实现"><a href="#Index-首页的实现" class="headerlink" title="Index 首页的实现"></a>Index 首页的实现</h4><h2 id="深入-Django-模型层"><a href="#深入-Django-模型层" class="headerlink" title="深入 Django 模型层"></a>深入 Django 模型层</h2><h3 id="跨DB迁移——模型层使用至数据库迁移"><a href="#跨DB迁移——模型层使用至数据库迁移" class="headerlink" title="跨DB迁移——模型层使用至数据库迁移"></a>跨DB迁移——模型层使用至数据库迁移</h3><h4 id="迁移的必要性"><a href="#迁移的必要性" class="headerlink" title="迁移的必要性"></a>迁移的必要性</h4><p>sqlite3在项目开发初期便利</p>
<p>sqlite3是文件数据库，性能跟不上</p>
<p>mysql是工业界非常常用的数据库</p>
<h4 id="迁移的过程"><a href="#迁移的过程" class="headerlink" title="迁移的过程"></a>迁移的过程</h4><h5 id="数据备份"><a href="#数据备份" class="headerlink" title="数据备份"></a>数据备份</h5><p>python manage.py dumpdate authorization &gt; authorization_data.json</p>
<h5 id="表结构同步配置"><a href="#表结构同步配置" class="headerlink" title="表结构同步配置"></a>表结构同步配置</h5><p>创建Mysql数据库并更新配置</p>
<p>创建slave数据库</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">DATABASES = &#123;</span><br><span class="line">    &apos;default&apos;: &#123;</span><br><span class="line">        &apos;ENGINE&apos;: &apos;django.db.backends.sqlite3&apos;,</span><br><span class="line">        &apos;NAME&apos;: os.path.join(BASE_DIR, &apos;db.sqlite3&apos;),</span><br><span class="line">    &#125;,</span><br><span class="line">    &apos;slave&apos;: &#123;</span><br><span class="line">        &apos;ENGINE&apos;: &apos;django.db.backends.mysql&apos;,</span><br><span class="line">        &apos;NAME&apos;: &apos;backend&apos;,</span><br><span class="line">        &apos;USER&apos;: &apos;root&apos;,</span><br><span class="line">        &apos;PASSWORD&apos;: &apos;&apos;,</span><br><span class="line">        &apos;HOST&apos;: &apos;127.0.0.1&apos;,</span><br><span class="line">        &apos;PORT&apos;: &apos;3306&apos;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 可以同时支持多个数据库，但是仅仅只有default默认数据库挂掉以后启动第二个</span><br><span class="line">&apos;&apos;&apos;</span><br><span class="line">DATABASES = &#123;</span><br><span class="line">    &apos;default&apos;: &#123;</span><br><span class="line">        &apos;ENGINE&apos;: &apos;django.db.backends.mysql&apos;,</span><br><span class="line">        &apos;NAME&apos;: &apos;backend&apos;,</span><br><span class="line">        &apos;USER&apos;: &apos;root&apos;,</span><br><span class="line">        &apos;PASSWORD&apos;: &apos;&apos;,</span><br><span class="line">        &apos;HOST&apos;: &apos;127.0.0.1&apos;,</span><br><span class="line">        &apos;PORT&apos;: &apos;3306&apos;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>表结构的同步</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manager.py migrate --run-syncdb --database slave</span><br></pre></td></tr></table></figure>
<h5 id="数据迁移"><a href="#数据迁移" class="headerlink" title="数据迁移"></a>数据迁移</h5><p>python manager.py loaddata authorization_data.json</p>
<h3 id="数据库索引——模型层使用之索引"><a href="#数据库索引——模型层使用之索引" class="headerlink" title="数据库索引——模型层使用之索引"></a>数据库索引——模型层使用之索引</h3><h4 id="索引的概述"><a href="#索引的概述" class="headerlink" title="索引的概述"></a>索引的概述</h4><p>索引是对数据库表中一列或多列的值进行排序的一种结构，使用索引可快速访问数据库表中的特定信息。如果想按特定职员的姓来查找他或她，则与在表中搜索所有的行相比，索引有助于更快地获取信息。<br>索引的一个主要目的就是加快检索表中数据，亦即能协助信息搜索者尽快的找到符合限制条件的记录ID的辅助数据结构。</p>
<p>优点：<br>加快检索数据的速度<br>降低插入、删除、更新的速度</p>
<h4 id="应该被索引的字段"><a href="#应该被索引的字段" class="headerlink" title="应该被索引的字段"></a>应该被索引的字段</h4><p>需要排序操作的字段(order_by)</p>
<p>需要比较操作的字段(&gt; &lt;&gt;)</p>
<p>需要过滤操作的字段(fluter)</p>
<h4 id="添加索引的两种方法"><a href="#添加索引的两种方法" class="headerlink" title="添加索引的两种方法"></a>添加索引的两种方法</h4><h5 id="属性中定义"><a href="#属性中定义" class="headerlink" title="属性中定义"></a>属性中定义</h5><p>nickname = models.CharField(max_length=256,db_index=True)</p>
<h5 id="模型的Meta添加索引"><a href="#模型的Meta添加索引" class="headerlink" title="模型的Meta添加索引"></a>模型的Meta添加索引</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class Meta: </span><br><span class="line">    indexes = [</span><br><span class="line">        models.Index(fields=[&apos;nickname&apos;]),</span><br><span class="line">        models.Index(fields=[&apos;open_id&apos;, &apos;nickname&apos;])</span><br><span class="line">    ]</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">组合索引是什么？组合索引建立的原则。b树和b+树的区别。</span><br><span class="line"></span><br><span class="line">一次查询只能用到一个索引，所以 首先枪毙 a，b各建索引方案</span><br><span class="line"></span><br><span class="line">a还是b？ 谁的区分度更高（同值的最少），建谁！</span><br><span class="line"></span><br><span class="line">当然，联合索引也是个不错的方案，ab，还是ba，则同上，区分度高者，在前</span><br><span class="line"></span><br><span class="line">索引用于快速找出在某个列中有一特定值的行。不使用索引，MySQL必须从第1条记录开始然后读完整个表直到找出相关的行，还需要考虑每次读入数据页的IO开销。而如果采取索引，则可以根据索引指向的页以及记录在页中的位置，迅速地读取目标页进而获取目标记录。</span><br><span class="line"></span><br><span class="line">大多数情况下都（默认）采用B树来构建索引。只是空间列类型的索引使用R-树，并且MEMORY表还支持hash索引。B树是平衡多叉树，每个节点存放多少个值取决于值所占的空间，这与每一张数据页存放多少条记录与记录信息量有关同理。节点中的值是以非降序进行排列的，节点中的值总是小于等于指向它的结点中的值。</span><br><span class="line"></span><br><span class="line">MySQL使用B树构造索引的情况下，是由叶子指向具体的页和记录的。并且一个叶子有一个指针指向下一个叶子。</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">Django模型类的Meta是一个内部类，它用于定义一些Django模型类的行为特性。而可用的选项大致包含以下几类</span><br><span class="line"></span><br><span class="line">abstract</span><br><span class="line">这个属性是定义当前的模型是不是一个抽象类。所谓抽象类是不会对应数据库表的。一般我们用它来归纳一些公共属性字段，然后继承它的子类可以继承这些字段。</span><br><span class="line"></span><br><span class="line">Options.abstract</span><br><span class="line">如果abstract = True 这个model就是一个抽象类</span><br><span class="line"></span><br><span class="line">app_label</span><br><span class="line">这个选型只在一种情况下使用，就是你的模型不在默认的应用程序包下的models.py文件中，这时候需要指定你这个模型是哪个应用程序的。</span><br><span class="line"></span><br><span class="line">Options.app_label</span><br><span class="line">如果一个model定义在默认的models.py，例如如果你的app的models在myapp.models子模块下，你必须定义app_label让Django知道它属于哪一个app</span><br><span class="line">app_label = &apos;myapp&apos;</span><br><span class="line"></span><br><span class="line">db_table</span><br><span class="line">db_table是指定自定义数据库表明的。Django有一套默认的按照一定规则生成数据模型对应的数据库表明。</span><br><span class="line">Options.db_table</span><br><span class="line">定义该model在数据库中的表名称</span><br><span class="line">　　db_table = &apos;Students&apos;</span><br><span class="line">如果你想使用自定义的表名，可以通过以下该属性</span><br><span class="line">　　table_name = &apos;my_owner_table&apos;</span><br><span class="line"></span><br><span class="line">db_teblespace</span><br><span class="line">Options.db_teblespace</span><br><span class="line">定义这个model所使用的数据库表空间。如果在项目的settin中定义那么它会使用这个值</span><br><span class="line"></span><br><span class="line">get_latest_by</span><br><span class="line">Options.get_latest_by</span><br><span class="line">在model中指定一个DateField或者DateTimeField。这个设置让你在使用model的Manager上的lastest方法时，默认使用指定字段来排序</span><br><span class="line"></span><br><span class="line">managed</span><br><span class="line">Options.managed</span><br><span class="line">默认值为True，这意味着Django可以使用syncdb和reset命令来创建或移除对应的数据库。默认值为True,如果你不希望这么做，可以把manage的值设置为False</span><br><span class="line"></span><br><span class="line">order_with_respect_to</span><br><span class="line">这个选项一般用于多对多的关系中，它指向一个关联对象，就是说关联对象找到这个对象后它是经过排序的。指定这个属性后你会得到一个get_xxx_order()和set_xxx_order()的方法，通过它们你可以设置或者回去排序的对象</span><br><span class="line"></span><br><span class="line">ordering</span><br><span class="line">这个字段是告诉Django模型对象返回的记录结果集是按照哪个字段排序的。这是一个字符串的元组或列表，没有一个字符串都是一个字段和用一个可选的表明降序的&apos;-&apos;构成。当字段名前面没有&apos;-&apos;时，将默认使用升序排列。使用&apos;?&apos;将会随机排列</span><br><span class="line"></span><br><span class="line">ordering=[&apos;order_date&apos;] # 按订单升序排列</span><br><span class="line">ordering=[&apos;-order_date&apos;] # 按订单降序排列，-表示降序</span><br><span class="line">ordering=[&apos;?order_date&apos;] # 随机排序，？表示随机</span><br><span class="line">ordering=[&apos;-pub_date&apos;,&apos;author&apos;] # 以pub_date为降序，在以author升序排列</span><br><span class="line">permissions</span><br><span class="line">permissions主要是为了在Django Admin管理模块下使用的，如果你设置了这个属性可以让指定的方法权限描述更清晰可读。Django自动为每个设置了admin的对象创建添加，删除和修改的权限。</span><br><span class="line">permissions = ((&apos;can_deliver_pizzas&apos;,&apos;Can deliver pizzas&apos;))</span><br><span class="line"></span><br><span class="line">proxy</span><br><span class="line">这是为了实现代理模型使用的，如果proxy = True,表示model是其父的代理 model </span><br><span class="line"></span><br><span class="line">unique_together</span><br><span class="line">unique_together这个选项用于：当你需要通过两个字段保持唯一性时使用。比如假设你希望，一个Person的FirstName和LastName两者的组合必须是唯一的，那么需要这样设置：</span><br><span class="line">unique_together = ((&quot;first_name&quot;, &quot;last_name&quot;),)</span><br><span class="line">一个ManyToManyField不能包含在unique_together中。如果你需要验证关联到ManyToManyField字段的唯一验证，尝试使用signal(信号)或者明确指定through属性。</span><br><span class="line"></span><br><span class="line">verbose_name</span><br><span class="line">verbose_name的意思很简单，就是给你的模型类起一个更可读的名字一般定义为中文，我们：</span><br><span class="line">verbose_name = &quot;学校&quot;</span><br><span class="line"></span><br><span class="line">verbose_name_plural</span><br><span class="line">这个选项是指定，模型的复数形式是什么，比如：</span><br><span class="line">verbose_name_plural = &quot;学校&quot;</span><br><span class="line">如果不指定Django会自动在模型名称后加一个’s’</span><br></pre></td></tr></table></figure>
<h4 id="关系映射实战"><a href="#关系映射实战" class="headerlink" title="关系映射实战"></a>关系映射实战</h4><h5 id="有没有用到关系映射实战"><a href="#有没有用到关系映射实战" class="headerlink" title="有没有用到关系映射实战"></a>有没有用到关系映射实战</h5><h5 id="用到哪种关系映射"><a href="#用到哪种关系映射" class="headerlink" title="用到哪种关系映射"></a>用到哪种关系映射</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">from django.db import models</span><br><span class="line"></span><br><span class="line">class Wife(models.Model):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line">class Husband(models.Model):</span><br><span class="line">    wife = models.OneToOneField(Wife,on_delete=models.CASCADE)</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line">class Mother(models.Model):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line">class Father(models.Model):</span><br><span class="line">    Wife = models.OneToOneField(Mother, on_delete=models.DO_NOTHING)</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line">class YoungerBrother(models.Model):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line">class ElderBrother(models.Model):</span><br><span class="line">    father_id = models.ForeignKey(Father,on_delete=models.DO_NOTHING)</span><br><span class="line">    younger_brother = models.ManyToManyField(YoungerBrother)</span><br><span class="line">    pass</span><br></pre></td></tr></table></figure>
<h3 id="增删改查——模型层使用之数据库操作"><a href="#增删改查——模型层使用之数据库操作" class="headerlink" title="增删改查——模型层使用之数据库操作"></a>增删改查——模型层使用之数据库操作</h3><h3 id="模型层关系映射——模型层使用之关系映射"><a href="#模型层关系映射——模型层使用之关系映射" class="headerlink" title="模型层关系映射——模型层使用之关系映射"></a>模型层关系映射——模型层使用之关系映射</h3><h4 id="三种关系映射"><a href="#三种关系映射" class="headerlink" title="三种关系映射"></a>三种关系映射</h4><p>一对一的关系：OneToOneField</p>
<p>一对多的关系：ForeignKey</p>
<p>多对多的关系：ManyToManyfield</p>
<h3 id="Django-MTV-中的M-Model"><a href="#Django-MTV-中的M-Model" class="headerlink" title="Django MTV 中的M: Model"></a>Django MTV 中的M: Model</h3><h3 id="Django-ORM-框架"><a href="#Django-ORM-框架" class="headerlink" title="Django ORM 框架"></a>Django ORM 框架</h3><p><img src="http://tuchuang.xchcloud.cn/ORM%20%E6%A8%A1%E5%9E%8B.jpg" alt="ORM"><br>优点：屏蔽数据库差异；提供迁移工具；简化开发流程.</p>

      
    </div>
    
    
    

      <div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>

<div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/python-Django框架-微信小助手实践/">python-Django框架-微信小助手实践</a></p>
  <p><span>文章作者:</span></a>Chao</p>
  <p><span>发布时间:</span>2019年03月31日 - 16:03</p>
  <p><span>最后更新:</span>2019年03月31日 - 20:03</p>
  <p><span>原始链接:</span><a href="/python-Django框架-微信小助手实践/" title="python-Django框架-微信小助手实践">http://xchcloud.cn/python-Django框架-微信小助手实践/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://xchcloud.cn/python-Django框架-微信小助手实践/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
</div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" <i class="fa fa-tag"></i> python</a>
          
            <a href="/tags/Django/" <i class="fa fa-tag"></i> Django</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019年3月学习笔记/" rel="next" title="2019年3月学习笔记">
                <i class="fa fa-chevron-left"></i> 2019年3月学习笔记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/python-Flask框架-鱼书网站实践/" rel="prev" title="python-Flask框架-鱼书网站实践">
                python-Flask框架-鱼书网站实践 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://tuchuang-xchcloud-1253428588.cos.ap-chengdu.myqcloud.com/blog/header.jpg"
               alt="John Doe" />
          </span></a>Chao</p>


           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">60</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">33</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">65</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/lhc0101" target="_blank" title="Github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                    
                      Github
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=qJmcmp_akJ6ZmZHo2dmGy8fF" target="_blank" title="E-mail">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                    
                      E-mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              dalao&nbsp;
              <i class="fa  fa-fw fa-globe"></i>
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://giracle.cn" title="DJG" target="_blank">DJG</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://owencxc.github.io" title="CX" target="_blank">CX</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.myzwl.win" title="ZWL" target="_blank">ZWL</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuliekun.me/" title="WLK" target="_blank">WLK</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://Li-rr.github.io" title="LRR" target="_blank">LRR</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://dh.xchcloud.cn" title="导航" target="_blank">导航</a>
                </li>
              
            </ul>
+        <div id="days"></div>
</script>
<script language="javascript">
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("06/26/2018 12:00:00");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>

          </div>
         

-        <div id="days"></div>
</script>
<script language="javascript">
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("06/26/2018 12:00:00");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#小程序基础"><span class="nav-number">1.</span> <span class="nav-text">小程序基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#全局配置（页面导航）"><span class="nav-number">1.1.</span> <span class="nav-text">全局配置（页面导航）</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#pages-列表配置"><span class="nav-number">1.1.1.</span> <span class="nav-text">pages 列表配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#window-属性配置"><span class="nav-number">1.1.2.</span> <span class="nav-text">window 属性配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#tabbar-配置"><span class="nav-number">1.1.3.</span> <span class="nav-text">tabbar 配置</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小程序的页面设置"><span class="nav-number">1.2.</span> <span class="nav-text">小程序的页面设置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#开启下拉刷新"><span class="nav-number">1.2.1.</span> <span class="nav-text">开启下拉刷新</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小程序的注册逻辑层"><span class="nav-number">1.3.</span> <span class="nav-text">小程序的注册逻辑层</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#小程序的注册逻辑"><span class="nav-number">1.3.1.</span> <span class="nav-text">小程序的注册逻辑</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#页面注册逻辑"><span class="nav-number">1.3.2.</span> <span class="nav-text">页面注册逻辑</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#页面数据"><span class="nav-number">1.3.2.1.</span> <span class="nav-text">页面数据</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#页面生命周期"><span class="nav-number">1.3.2.2.</span> <span class="nav-text">页面生命周期</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小程序的视图层"><span class="nav-number">1.4.</span> <span class="nav-text">小程序的视图层</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#数据绑定"><span class="nav-number">1.4.1.</span> <span class="nav-text">数据绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#列表渲染"><span class="nav-number">1.4.2.</span> <span class="nav-text">列表渲染</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#条件渲染"><span class="nav-number">1.4.3.</span> <span class="nav-text">条件渲染</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#绑定事件"><span class="nav-number">1.4.4.</span> <span class="nav-text">绑定事件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#小程序框架"><span class="nav-number">1.4.5.</span> <span class="nav-text">小程序框架</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小程序提供的能力和常用的API"><span class="nav-number">1.5.</span> <span class="nav-text">小程序提供的能力和常用的API</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#微信API"><span class="nav-number">1.5.1.</span> <span class="nav-text">微信API</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#网络请求"><span class="nav-number">1.5.1.1.</span> <span class="nav-text">网络请求</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#HTTP请求"><span class="nav-number">1.5.1.1.1.</span> <span class="nav-text">HTTP请求</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#文件上传、下载"><span class="nav-number">1.5.1.1.2.</span> <span class="nav-text">文件上传、下载</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#Task（网络任务对象）"><span class="nav-number">1.5.1.1.3.</span> <span class="nav-text">*Task（网络任务对象）</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#本地存储"><span class="nav-number">1.5.1.2.</span> <span class="nav-text">本地存储</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#文件系统"><span class="nav-number">1.5.2.</span> <span class="nav-text">文件系统</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#提供一个全局的问价管理系统，来实现对文件的增删改查"><span class="nav-number">1.5.2.1.</span> <span class="nav-text">提供一个全局的问价管理系统，来实现对文件的增删改查</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#文件夹操作"><span class="nav-number">1.5.2.2.</span> <span class="nav-text">文件夹操作</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#开放能力"><span class="nav-number">1.5.3.</span> <span class="nav-text">开放能力</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#用户数据"><span class="nav-number">1.5.3.1.</span> <span class="nav-text">用户数据</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#基础组件"><span class="nav-number">1.5.3.2.</span> <span class="nav-text">基础组件</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Django视图层"><span class="nav-number">2.</span> <span class="nav-text">Django视图层</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#会话管理"><span class="nav-number">3.</span> <span class="nav-text">会话管理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#有状态服务"><span class="nav-number">3.1.</span> <span class="nav-text">有状态服务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是状态"><span class="nav-number">3.1.1.</span> <span class="nav-text">什么是状态</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小程序的状态管理"><span class="nav-number">4.</span> <span class="nav-text">小程序的状态管理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#小程序登录功能"><span class="nav-number">4.1.</span> <span class="nav-text">小程序登录功能</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#步骤"><span class="nav-number">4.1.1.</span> <span class="nav-text">步骤</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#完善用户的个人信息"><span class="nav-number">4.2.</span> <span class="nav-text">完善用户的个人信息</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#用户模型的变更"><span class="nav-number">4.2.1.</span> <span class="nav-text">用户模型的变更</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#修改个人信息的功能开发"><span class="nav-number">4.2.2.</span> <span class="nav-text">修改个人信息的功能开发</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复杂多变的用户状态管理"><span class="nav-number">4.3.</span> <span class="nav-text">复杂多变的用户状态管理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#有状态的应用服务"><span class="nav-number">4.3.1.</span> <span class="nav-text">有状态的应用服务</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Index-首页的实现"><span class="nav-number">4.3.2.</span> <span class="nav-text">Index 首页的实现</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#深入-Django-模型层"><span class="nav-number">5.</span> <span class="nav-text">深入 Django 模型层</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#跨DB迁移——模型层使用至数据库迁移"><span class="nav-number">5.1.</span> <span class="nav-text">跨DB迁移——模型层使用至数据库迁移</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#迁移的必要性"><span class="nav-number">5.1.1.</span> <span class="nav-text">迁移的必要性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#迁移的过程"><span class="nav-number">5.1.2.</span> <span class="nav-text">迁移的过程</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#数据备份"><span class="nav-number">5.1.2.1.</span> <span class="nav-text">数据备份</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#表结构同步配置"><span class="nav-number">5.1.2.2.</span> <span class="nav-text">表结构同步配置</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#数据迁移"><span class="nav-number">5.1.2.3.</span> <span class="nav-text">数据迁移</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库索引——模型层使用之索引"><span class="nav-number">5.2.</span> <span class="nav-text">数据库索引——模型层使用之索引</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#索引的概述"><span class="nav-number">5.2.1.</span> <span class="nav-text">索引的概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#应该被索引的字段"><span class="nav-number">5.2.2.</span> <span class="nav-text">应该被索引的字段</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#添加索引的两种方法"><span class="nav-number">5.2.3.</span> <span class="nav-text">添加索引的两种方法</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#属性中定义"><span class="nav-number">5.2.3.1.</span> <span class="nav-text">属性中定义</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#模型的Meta添加索引"><span class="nav-number">5.2.3.2.</span> <span class="nav-text">模型的Meta添加索引</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#关系映射实战"><span class="nav-number">5.2.4.</span> <span class="nav-text">关系映射实战</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#有没有用到关系映射实战"><span class="nav-number">5.2.4.1.</span> <span class="nav-text">有没有用到关系映射实战</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#用到哪种关系映射"><span class="nav-number">5.2.4.2.</span> <span class="nav-text">用到哪种关系映射</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#增删改查——模型层使用之数据库操作"><span class="nav-number">5.3.</span> <span class="nav-text">增删改查——模型层使用之数据库操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模型层关系映射——模型层使用之关系映射"><span class="nav-number">5.4.</span> <span class="nav-text">模型层关系映射——模型层使用之关系映射</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#三种关系映射"><span class="nav-number">5.4.1.</span> <span class="nav-text">三种关系映射</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Django-MTV-中的M-Model"><span class="nav-number">5.5.</span> <span class="nav-text">Django MTV 中的M: Model</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Django-ORM-框架"><span class="nav-number">5.6.</span> <span class="nav-text">Django ORM 框架</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chao</span>
</div>



<div class="theme-info">
  <span class="post-count">博客全站共118.7k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">访客总量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  









  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/three/three.min.js"></script>

  
  <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.2"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.2"></script>


  

  

</body>
</html>
